﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;

namespace AutoGam
{
    public partial class ShippingForm : Form
    {
        /// <summary>
        /// 数据库连接参数
        /// </summary>
        private String conStr = "";

        private String oldCardNo = "";
        private bool needSwitch = false;

        private void init()
        {
            //文件路径
            string filePath = System.Environment.CurrentDirectory + @"\config.ini";
            try
            {
                if (File.Exists(filePath))
                {
                    conStr = File.ReadAllText(filePath);
                }
                else
                {
                    MessageBox.Show("配置文件不存在");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private OperateInfo info = new OperateInfo();

        private class OperateInfo
        {
            /// <summary>
            /// 车牌号
            /// </summary>
            private String carNo = "";

            public String CarNo
            {
                get { return carNo; }
                set { carNo = value; }
            }
            /// <summary>
            /// 发放的磁卡序列号
            /// </summary>
            private String cardSerial = "";

            public String CardSerial
            {
                get { return cardSerial; }
                set { cardSerial = value; }
            }

            private String cardNo = "";
            /// <summary>
            /// 发放的磁卡编号
            /// </summary>
            public String CardNo
            {
                get { return cardNo; }
                set { cardNo = value; }
            }

            /// <summary>
            /// 订单ID
            /// </summary>
            private int orderID = 0;

            public int OrderID
            {
                get { return orderID; }
                set { orderID = value; }
            }
            /// <summary>
            /// 固定卡号
            /// </summary>
            private String custCardNo = "";

            public String CustCardNo
            {
                get { return custCardNo; }
                set { custCardNo = value; }
            }
            /// <summary>
            /// 销售计划ID
            /// </summary>        
            private int salePlanID = 0;

            public int SalePlanID
            {
                get { return salePlanID; }
                set { salePlanID = value; }
            }
            /// <summary>
            /// 物料名称
            /// </summary>
            private String materialName;

            public String MaterialName
            {
                get { return materialName; }
                set { materialName = value; }
            }

            private String materialID;

            public String MaterialID
            {
                get { return materialID; }
                set { materialID = value; }
            }

            private Decimal yz = 0;
            /// <summary>
            /// 额定预装数量
            /// </summary>
            public Decimal Yz
            {
                get { return yz; }
                set { yz = value; }
            }

        }

        private class SalesPlanInfo 
        {
            private int fid;

            public int Fid
            {
                get { return fid; }
                set { fid = value; }
            }
            private Decimal num;

            public Decimal Num
            {
                get { return num; }
                set { num = value; }
            }
        
            
        }

        public ShippingForm()
        {
            InitializeComponent();
            init();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

            if (!Program.IsDebug)
            {
                this.TopMost = true;
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void PageSales_NumNext_Click(object sender, EventArgs e)
        {
            //PageSales_NumMessage.Text = Device.UsbCardDevice.GetSerial();
            //PageSales_NumMessage.Text = PageSales_NumMessage + "    " + Device.MHCardDevice.GetSerial();
            needSwitch = true;
            Device.ButtonVoice();
            if (!info.CustCardNo.Equals("") && !info.CarNo.Equals(""))
            {
                String sql = @"select isnull(a.FComboBox4,'') gk,isnull(a.FText,'') shipNo,isnull(a.FText2,'') bgNo,a.FBillNo billNo,a.FID,b.FName Material,b.fid MaterialID,a.FDecimal num from KEW_SalesPlan a
                                left join KEW_Products b on b.FID = a.FBase1
                                where FMultiCheckStatus = 16 and FComboBox2 in (0,1) and FCheckBox1 = 1
                                select * from KEW_SalesInfo where ftext = '" + info.CarNo + "' and FComboBox < 3 and FCheckBox4 = 0 ";
                DataSet ds = query(sql,conStr);
                if (ds != null && ds.Tables.Count > 1 && ds.Tables[1].Rows.Count > 0)
                {
                    PageSales_NumMessage.ForeColor = Color.Red;
                    PageSales_NumMessage.Text = "厂内存在相同车牌号车辆，禁止开卡！";
                }
                else
                {
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        salePlanListView.Items.Clear();
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ListViewItem item = new ListViewItem();
                            item.Text = "港口：" + ds.Tables[0].Rows[i]["gk"].ToString() + "    报港单号:" + ds.Tables[0].Rows[i]["bgNo"].ToString()
                                        + "   计划单号:" + ds.Tables[0].Rows[i]["billNo"].ToString()
                                        + "   船号：" + ds.Tables[0].Rows[i]["shipNo"].ToString();
                            item.ImageIndex = i;
                            item.Name = ds.Tables[0].Rows[i]["fid"].ToString();
                            info.MaterialName = ds.Tables[0].Rows[i]["Material"].ToString();
                            info.MaterialID = ds.Tables[0].Rows[i]["MaterialID"].ToString();
                            SalesPlanInfo plan = new SalesPlanInfo();
                            plan.Fid = Int32.Parse(ds.Tables[0].Rows[i]["fid"].ToString());
                            plan.Num = Decimal.Parse(ds.Tables[0].Rows[i]["num"].ToString());
                            item.Tag = plan;
                            salePlanListView.Items.Add(item);
                        }
                    }
                    SalesTab.SelectedTab = TabPageSalePlan;
                }
            }
            else 
            {
                PageSales_NumMessage.ForeColor = Color.Red;
                PageSales_NumMessage.Text = "请将固定卡放到指定位置";
            }
            needSwitch = false;
        }

        private void PageSales_NumCancel_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            Close();
        }

        private void MainTimer_Tick(object sender, EventArgs e)
        {
            info.CustCardNo = Device.MHCardDevice.GetSerial();
            if (!info.CustCardNo.Equals(""))
            {
                if (!oldCardNo.Equals(info.CustCardNo))
                {
                    oldCardNo = info.CustCardNo;
                    String sql = @"select isnull(a.FText,'') CarNo,convert(decimal(10,2),a.FDecimal) YZ,isnull(a.FCheckBox,0) Forbid from KEW_PortCard a
                                left join Cardserver.dbo.KEW_ICCard b on a.FText1 = b.FNumber
                                left join Cardserver.dbo.KEW_ICCardEntry c on c.fid = b.FID
                                where c.FText = '" + info.CustCardNo + @"' and a.FCheckBox = 0 ";
                    DataSet ds = query(sql, conStr);
                    String message = "";
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        message = "车牌号: " + ds.Tables[0].Rows[0]["CarNo"].ToString() + " \r\n\r\n"
                                        + "额定预装量: " + ds.Tables[0].Rows[0]["YZ"].ToString() + " \r\n";
                        info.CarNo = ds.Tables[0].Rows[0]["CarNo"].ToString();
                        info.Yz = Decimal.Parse(ds.Tables[0].Rows[0]["YZ"].ToString());
                        PageSales_NumMessage.ForeColor = Color.White;
                    }
                    else
                    {
                        message = "未查询到该卡片信息！";
                        info.CarNo = "";
                        PageSales_NumMessage.ForeColor = Color.Red;
                    }
                    PageSales_NumMessage.Text = message;
                }
            }
            else
            {
                oldCardNo = "";
            }
        }

        public DataSet query(String sql, String connectString)
        {
            SqlConnection con = null;
            DataSet ds = null;
            SqlCommand com = null;
            try
            {
                con = new SqlConnection(connectString);
                con.Open();
                com = new SqlCommand(sql, con);
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.SelectCommand = com;
                ds = new DataSet();
                adapter.Fill(ds);
            }
            catch (Exception ex)
            {
                ds = null;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (com != null)
                {
                    com.Dispose();
                }
                if (con != null && con.State != ConnectionState.Closed)
                {
                    con.Close();
                }
            }
            return ds;
        }

        private void PagePlan_Next_Click(object sender, EventArgs e)
        {
            needSwitch = true;
            Device.ButtonVoice();
            info.SalePlanID = 0;
            ListViewItem item = null;
            for (int i = 0; i < salePlanListView.Items.Count; i++)
            {
                if (salePlanListView.Items[i].Selected)
                {
                    info.SalePlanID = Int32.Parse(salePlanListView.Items[i].Name);
                    item = salePlanListView.Items[i];
                    break;
                }
            }
            if (info.SalePlanID != 0 && item != null)
            {
                String sql = @"declare @yz decimal(10,2)
                                declare @cc decimal(10,2)
                                declare @count int
                                select @cc = isnull(SUM(FDecimal3),0) from KEW_SalesInfo 
                                where FID_SRC1 = " + info.SalePlanID.ToString() + @" and FCheckBox4 = 0 and FComboBox = 3 
                                select @yz = isnull(SUM(FDecimal4),0) from KEW_SalesInfo 
                                where FID_SRC1 = " + info.SalePlanID.ToString() + @" and FCheckBox4 = 0 and FComboBox < 3
                                select @count = COUNT(*) from KEW_SalesInfo 
                                where FID_SRC1 = " + info.SalePlanID.ToString() + @" and FCheckBox4 = 0 and FComboBox < 3
                                select isnull(@yz + @cc,0) usedNum,isnull(@count,0) carsIn";
                DataSet ds = query(sql,conStr);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) 
                {
                    SalesPlanInfo plan = (SalesPlanInfo)item.Tag;
                    Decimal yz = 0;
                    if ((plan.Num - Decimal.Parse(ds.Tables[0].Rows[0]["usedNum"].ToString())) >= info.Yz)
                    {
                        yz = info.Yz;
                    }
                    else 
                    {
                        if (Int32.Parse(ds.Tables[0].Rows[0]["carsIn"].ToString()) == 0)
                        {
                            yz = plan.Num - Decimal.Parse(ds.Tables[0].Rows[0]["usedNum"].ToString());
                        }
                        else 
                        {
                            PageCar_Message.Text = "该计划余量不足,不能开票！";
                            return;
                        }                        
                    }
                    PageConfirmCar.Text = info.CarNo;
                    PageConfirmItem.Text = info.MaterialName;
                    PageConfirmQty.Text = yz.ToString("0.00");
                    PageConfirmPlan.Text = item.Text;
                    SalesTab.SelectedTab = TabPageSalesConfirm;
                }
            }
            else
            {
                //MessageBox.Show("请选择计划单！");
            }
            needSwitch = false;
        }

        private void PageConfirm_Next_Click(object sender, EventArgs e)
        {
            needSwitch = true;
            //Device.Voice("voice1.wav");
            Device.ButtonVoice();
            //Device.GetCard();
            //info.CardSerial = Device.UsbCardDevice.GetSerial();
            info.CardSerial = Device.GetCardAndReturnSerial();
            if (info.CardSerial == null || info.CardSerial.Equals(""))
            {
                MessageBox.Show("磁卡已用光，请联系管理员处理！");
            }
            else
            {
                String sql = "exec CM_ShipAutoSendCard '" + info.CarNo +"'," + info.SalePlanID + ",'" + info.CardSerial + "',"
                                + info.Yz + "," + info.MaterialID + ",'" + Guid.NewGuid().ToString() + "','" 
                                + info.CustCardNo + "'";
                DataSet ds = query(sql,conStr);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0][0].ToString().Equals("TRUE"))
                    {
                        PageConfirm_Message.Text = "请取走您的磁卡！";
                        Device.SendCard();
                        Device.CountDown = 6;
                    }
                    else 
                    {
                        PageConfirm_Message.Text = ds.Tables[0].Rows[0][1].ToString();
                    }
                }
                else
                {
                    PageConfirm_Message.Text = "操作失败！";
                }
                
            }
            needSwitch = true;
        }

        private void SalesTab_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (!needSwitch) 
            {
                e.Cancel = true;
            }
        }

        private void PageConfirm_Return_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            Close();
        }

        private void PageCar_Cancel_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            Close();
        }

        private void ButtonTimer_Tick(object sender, EventArgs e)
        {
            if (Device.CountDown > 0)
            {
                Device.CountDown--;
            }
            else if (Device.CountDown == 0)
            {
                this.Close();
            }

            label7.Text = Device.UsbCardDevice.Flag;
        }
    }
}
